package com.quan.weixin.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mzlion.easyokhttp.HttpClient;
import com.quan.weixin.common.WeixinContext;

/**
 * 获取 JsApiTicket 票据
 */
public class JsTicketApi {
	
	private static Logger logger = LoggerFactory.getLogger(JsTicketApi.class);
	
	private static int repeat = 3;
	
	/**
	 * JSApi的类型
	 * <br>jsapi: 用于分享等js-api
	 * <br>wx_card：用于卡券接口签名凭证api_ticket
	 */
	public enum JsApiType {
		jsapi, wx_card
	}

	public static JsTicket getJsTicket(JsApiType jsApiType) {
		String url = API.get(API.JS_API_TICKET_URL, WeixinContext.getAccessToken(), null == jsApiType ? JsApiType.jsapi.name() : jsApiType.name()) ;
		
		JsTicket ticket = HttpClient.get(url).execute().asBean(JsTicket.class) ;
		
		if(ticket.getErrcode() > 0) {
			logger.error("微信JsApi-Ticket票据获取[失败]：{}", ticket.getErrmsg());
			repeat -- ;
			if(repeat > 0)
				getJsTicket(jsApiType) ;
		} else {
			repeat = 3 ;
		}
		logger.info("微信JsApi-Ticket票据获取[成功]:{}", ticket);
		return ticket ;
	}
}
